function setLocation(url) {
	window.location.href = url;
};

GeneralTab = function(el) {
	function getTabId(a) {
		return '#' + a.href.replace(/.*?#/, '');
	}
	
	// hide all tab
	$(el + ' li > a').each(function (i, e) {
		if ($(e).parent().hasClass('active')) return;
		var tabId = getTabId(this);
		$(tabId).hide();
	});
	
	// show default tab
	var x = $(el + ' li.active > a')[0];
	if (typeof x == 'undefined') {
		var li = $(el + ' li:first');
		li.addClass('active');
		var tabId = getTabId(li.find('a')[0]);
		$(tabId).show();
	}
	
	// bind click event
	$(el + ' li > a').click(function (e) {
		// hide current tab
		var a = $(el + ' li.active > a')[0];
		var oldTab = getTabId(a);
		$(a).parent().removeClass('active');
		$(oldTab).hide();
		
		// show active tab
		var tabId = getTabId(this);
		$(tabId).show();
		$(this).parent().addClass('active');
		
		e.preventDefault();
	});
};

function formatFileSize(fileSizeInBytes) {
	var i = -1;
	var byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
	do {
		fileSizeInBytes = fileSizeInBytes / 1024;
		i++;
	} while (fileSizeInBytes > 1024);

	return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
};

function initGrid() {
	$('.table tbody tr').click(function () {
		setLocation(this.title);
	});
}

function initEditForm() {
	$('#btnSave').click(function (e) {
		$('#editForm').submit();
	});

	$('#btnSaveAndEdit').click(function (e) {
		var action = $('#editForm').attr('action') + '/back/1/';
		$('#editForm').attr('action', action);
		$('#editForm').submit();
	});
	
	$('#btnDelete').click(function (e) {
		var c = confirm('Are you sure to delete this item ?');
		if (!c) e.preventDefault();
	});
}

function initFileUpload(uploadUrl) {
	//serialize image list before form submit
	$('#editForm').submit(function (e) {
		var imgs = [];
		$('#imageList tbody tr').each(function () {
			var obj = {};
			obj.id = this.id.replace('r-', '');
			obj.sort_order = $(this).find('td:nth(1) input').val();
			obj.remove = $(this).find('td:nth(2) input')[0].checked;
			imgs.push(obj);
		});
		$('#post_gallery').val(JSON.stringify(imgs));
	});

	// init file uploader
	$('#fineUploader').fineUploader({
		request: {
			endpoint: uploadUrl
		},
		text: {
			uploadButton: '<i class="icon-plus icon-white"></i><span>Add files...</span>'
		},
		validation: {
			allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
			sizeLimit: 5242880, // 50 MB
			itemLimit: 3
		},
		autoUpload: false
	})
	.on('complete', function(event, id, name, responseJSON){
		if (!responseJSON.success) return;
		var row = '<tr id="r-'+responseJSON.id+'">'
			+'<td><img src="'+responseJSON.url+'" alt="" title="'+responseJSON.url+'" /></td>'
			+'<td><input type="text" value="0" class="input-mini" /></td>'
			+'<td><input type="checkbox" /></td>';
		$('#imageList tbody').append($(row));
	});

	$('#startUpload').click(function() {
		$('#fineUploader').fineUploader('uploadStoredFiles');
	});
}